package route

import (
	"encoding/json"
	"fmt"
	"net/http"
	"pdocker/config"
	"pdocker/docker"
	"pdocker/task/build"
	"pdocker/tool/ws"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
)

// @Summary 获取镜像列表
// @Tags docker
// @Description "查询全部镜像"
// @Produce json
// @Param task body []string true "镜像列表"
// @Success 200 {dict} docker.Image "["image1","image2"]"
// @Router /docker/image/list [post]
func ImageList(c *gin.Context) {
	var arr = new([]string)
	var existImage = make(map[string]string)
	var checkImage = make(map[string]bool)
	err := c.BindJSON(arr)
	if err != nil {
		c.String(http.StatusBadRequest, "格式错误")
	} else {
		for _, image := range build.ImageSummaries() {
			if len(image.RepoTags) > 0 && !strings.Contains(image.RepoTags[0], "none") {
				index := strings.Index(image.RepoTags[0], ":latest")
				if index != -1 {
					existImage[image.RepoTags[0][:index]] = image.ID
				}
			}
		}
		for _, key := range *arr {
			if _, ok := existImage[key]; ok {
				checkImage[key] = true
			} else {
				checkImage[key] = false
			}
		}
	}

	c.PureJSON(http.StatusOK, checkImage)
}

// @Summary 查询镜像
// @Tags docker
// @Description "查询镜像"
// @Param name path string true "获取镜像"
// @Produce json
// @Failure 400 {object} types.TaskResponse "{"code":400,"taskid":"","msg":"格式错误"}"
// @Success 200 {object} docker.Image "{"name":["name1","name2"],id:"sha256:abcd"}"
// @Router /docker/image/filter/{name} [get]
func ImageShow(c *gin.Context) {
	var i docker.ImageControl = &build.ImageTask{Name: c.Param("name")}
	image, err := i.Show()
	if err != nil {
		log.Error(err)
		simpleReturn(c, http.StatusBadRequest, "", err.Error())
	} else {
		c.PureJSON(http.StatusOK, image)
	}

}

// @Summary 构建镜像
// @Tags docker
// @Description "构建镜像"
// @Param task body build.BuildModel true "构建镜像参数"
// @Produce json
// @Success 200 {object} docker.Image "{"name":["name1","name2"],id:"sha256:abcd"}"
// @Router /docker/image/build [post]
func ImageBuild(c *gin.Context) {
	imageBuildModel := new(build.BuildModel)
	err := c.BindJSON(imageBuildModel)
	if err != nil {
		simpleReturn(c, http.StatusBadRequest, "", "格式错误")
	} else {
		go imageBuildModel.Build()
		simpleReturn(c, http.StatusOK, "", "开始构建")
	}
}
func ImageBuildWS(c *gin.Context) {
	wsConn, err := ws.UpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Error(err)
	}
	defer wsConn.Close()
	c.Writer.Header().Set("Content-Type", "application/json")

	for {
		_, message, err := wsConn.ReadMessage()
		if err != nil {
			log.Error(err)
			break
		}
		imageBuildModel := new(build.BuildModel)
		err = json.Unmarshal(message, imageBuildModel)
		if err != nil {
			_ = wsConn.WriteMessage(websocket.TextMessage, []byte("json解析错误"))
			c.Writer.Flush()
			log.Error("json解析错误", err)
		} else {
			imageBuildModel.Buildws(wsConn)
		}
	}
}

//func ImageBuilder(c *gin.Context) {
//	b := new(build.BuildModel)
//	err := c.BindJSON(b)
//	if err != nil {
//		simpleReturn(c, http.StatusBadRequest, "", "格式错误")
//	} else {
//		fmt.Println(b)
//		msg := docker.Builder(b.All, b.Filters, b.Force, b.Callback)
//		c.PureJSON(http.StatusOK, msg)
//	}
//
//	//var code string
//	//if err == nil {
//	//	code = "200"
//	//} else if strings.Index(err.Error(), "empty") == -1 {
//	//	code = "401"
//	//} else {
//	//	code = "404"
//	//}
//
//	//if err != nil {
//	//	log.Println(err)
//	//	return types.ImageBuildResponse{}, err
//	//}
//	//defer response.Body.Close()
//	//log.Println(response.OSType)
//	//var output bytes.Buffer
//	//termFd, isTerm := term.GetFdInfo(&output)
//	//_ = jsonmessage.DisplayJSONMessagesStream(response.Body, &output, termFd, isTerm, nil)
//	//config.BuildInformation[it.Name] = string(output.Bytes())
//	//log.Println(config.BuildInformation[it.Name])
//}

// @Summary 构建镜像结果
// @Tags docker
// @Description "构建镜像结果"
// @Param name path string true "查询镜像"
// @Produce json
// @Success 200 {string} string "FROM step 1\n FROM step2"
// @Router /docker/image/info/{name} [get]
func ImageBuilderInformation(c *gin.Context) {
	fmt.Println(config.BuildInformation[c.Param("name")])
	c.String(http.StatusOK, config.BuildInformation[c.Param("name")])
}
